package com.xixi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xixi.constant.UserConstant;
import com.xixi.mapper.UserMapper;
import com.xixi.model.domain.User;
import com.xixi.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.xixi.constant.UserConstant.*;

/**
* @author xixi
* @description 针对表【user(用户)】的数据库操作Service实现
* @createDate 2024-09-09 14:12:24
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService {

	private final UserMapper userMapper;

	// 盐值
	private static final String SALT = "xixi";

	public UserServiceImpl(UserMapper userMapper) {
		this.userMapper = userMapper;
	}

	@Override
	public long userRegister(String userAccount, String userPassword, String checkPassword) {
		// 1. 校验
		if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
			return -1;
		}
		if (userAccount.length() < 4) {
			return -1;
		}
		if (userPassword.length() < 8 || checkPassword.length() < 8) {
			return -1;
		}
		// 用户账户不能包含特殊字符
		String valid = "^\\w{4,10}$";
		Matcher matcher = Pattern.compile(valid).matcher(userAccount);
		if (!matcher.matches()) {
			return -1;
		}
		// 密码和校验密码相同
		if (!userPassword.equals(checkPassword)) {
			return -1;
		}
		// 账户不能重复
		QueryWrapper<User> wrapper = new QueryWrapper<>();
		wrapper.eq("userAccount", userAccount);
		long count = userMapper.selectCount(wrapper);
		if (count > 0) {
			return -1;
		}

		// 2. 加密密码
		String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());

		// 3. 插入数据
		User user = new User();
		user.setUserAccount(userAccount);
		user.setUserPassword(encryptPassword);
		boolean saved = this.save(user);
		if (!saved) {
			return -1;
		}
		return user.getId();
	}

	@Override
	public User doLogin(String userAccount, String userPassword, HttpServletRequest request) {
		// 1. 校验
		if (StringUtils.isAnyBlank(userAccount, userPassword)) {
			return null;
		}
		if (userAccount.length() < 4) {
			return null;
		}
		if (userPassword.length() < 8) {
			return null;
		}
		// 用户账户不能包含特殊字符
		String valid = "^\\w{4,10}$";
		Matcher matcher = Pattern.compile(valid).matcher(userAccount);
		if (!matcher.matches()) {
			return null;
		}

		// 2. 加密密码
		String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
		// 查询用户是否存在
		QueryWrapper<User> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("userAccount", userAccount);
		queryWrapper.eq("userPassword", encryptPassword);
		User user = userMapper.selectOne(queryWrapper);
		if (user == null) {
			log.info("user login failed, userAccount cannot match userPassword");
			return null;
		}

		// 3. 用户信息脱敏
		User safetyUser = new User();
		safetyUser.setId(user.getId());
		safetyUser.setUsername(user.getUsername());
		safetyUser.setUserAccount(user.getUserAccount());
		safetyUser.setAvatarUrl(user.getAvatarUrl());
		safetyUser.setGender(0);
		safetyUser.setPhone(user.getPhone());
		safetyUser.setEmail(user.getEmail());
		safetyUser.setUserStatus(user.getUserStatus());
		safetyUser.setCreateTime(user.getCreateTime());
		safetyUser.setUserRole(user.getUserRole());

		// 4. 记录用户登录态
		HttpSession session = request.getSession();
		session.setAttribute(UserConstant.USER_LOGIN_STATE, safetyUser);

		return safetyUser;
	}

	@Override
	public List<User> searchUser(String username, HttpServletRequest request) {
		// 仅管理员可查询
		if (!isAdmin(request)) {
			return new ArrayList<>();
		}
		QueryWrapper<User> queryWrapper = new QueryWrapper<>();
		if (StringUtils.isNotBlank(username)) {
			queryWrapper.like("username", username);
		}
		return this.list(queryWrapper);
	}

	@Override
	public Boolean deleteUser(Long userId, HttpServletRequest request) {
		// 仅管理员可以删除
		if (!isAdmin(request)) {
			return false;
		}
		if (userId <= 0) {
			return false;
		}
		return this.removeById(userId);
	}

	private boolean isAdmin(HttpServletRequest request) {
		Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
		User user = (User) userObj;
		return user != null && user.getUserRole() == ADMIN_ROLE;
	}
}




